
<template>
  <div class='app-container'>
    <el-row type='flex' :gutter='12'>
      <el-col :span='4'>
        <div class='left-tree'>
          <el-tree :data='productgroups' highlight-current :render-content='renderContent' :expand-on-click-node='false' :props='defaultProps' @current-change='onTreeSelected' empty-text='无可用输入分组' node-key='groupid' default-expand-all>
          </el-tree>
        </div>
      </el-col>
      <el-col :span='20'>
        <div class='right-grid'>
          <div class='button-container'>
            <el-button class='filter-item' type='primary' @click='editGood(null,true)' :disabled='selectedGroup==0' icon='edit'>新增</el-button>
          </div>
          <el-table ref='productTable' @selection-change='onSelectionChanged' :data='gridPageList' v-loading.body='gridDataIsLoading' element-loading-text='数据加载中...' border fit highlight-current-row>
            <el-table-column align='center' label='序号' width='80'>
              <template scope='scope'>
                {{scope.$index + 1}}
              </template>
            </el-table-column>
            <el-table-column label='名称' width='100'>
              <template scope='scope'>
                {{scope.row.basic.gsname}}
              </template>
            </el-table-column>
            <el-table-column label='价格' width='130'>
              <template scope='scope'>
                {{scope.row.basic.gsprice}}
              </template>
            </el-table-column>
            <el-table-column label='介绍文案' width='150'>
              <template scope='scope'>
                {{scope.row.basic.gsinfo}}
              </template>
            </el-table-column>
            <el-table-column label='备注' width='180'>
              <template scope='scope'>
                {{scope.row.basic.gsdescription}}
              </template>
            </el-table-column>
            <el-table-column align='center' label='操作'>
              <template scope='scope'>
                <el-button icon='edit' size='small' type='primary' @click=editGood(scope.row,false)>编辑</el-button>
                <el-button icon='delete' type='danger' size='small' @click='deletegood(scope.$index, scope.row)'>删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div v-show='!gridDataIsLoading' class='pagination-container'>
            <el-pagination @size-change='onPageSizeChanged' @current-change='onPageNoChanged' :current-page.sync='paginationConfig.currentQueryPage' :page-sizes='[10,20,30, 50]' :page-size='paginationConfig.selectedPageSize' layout='total, sizes, prev, pager, next, jumper' :total='dataCount'>
            </el-pagination>
          </div>
        </div>
      </el-col>
    </el-row>
    <el-dialog title='输入分组录入' :visible.sync='editGroupDialogOpend' class='group-dialog' @close='closeGroupForm'>
      <el-form :model='editingGroup' ref='groupForm' :rules='grouprules' :show-message='groupValidateable'>
        <el-form-item label='分组名称' prop='groupname'>
          <el-input v-model='editingGroup.groupname' placeholder='请输入分组名称'></el-input>
        </el-form-item>
        <el-form-item label='分组图标'>
          <el-select v-model='editingGroup.grouptype' placeholder='请选择分组图标'>
            <el-option label='立减' value='decrease'></el-option>
            <el-option label='折扣' value='discount'></el-option>
            <el-option label='特价' value='special'></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot='footer' class='dialog-footer'>
        <el-button type='primary' @click='handleEditGroupSubmit'>确定</el-button>
        <el-button @click='editGroupDialogOpend = false'>取消</el-button>
      </div>
    </el-dialog>

    <el-dialog title='录入货品' :visible.sync='editGoodDialogOpend' class='good-dialog' @close='closeGoodForm'>
      <el-form :model='editingGood' ref='goodForm' :rules='goodrules' :show-message='goodValidateable'>
        <el-form-item label='名称' prop='groupname'>
          <el-input v-model='editingGood.gsname' placeholder='请输入货品名称'></el-input>
        </el-form-item>
        <el-form-item label='价格' prop='gsprice'>
          <el-input-number v-model="editingGood.gsprice" :min="0" :controls="true" :step="0.05"></el-input-number>
        </el-form-item>
        <el-row type="flex">
          <el-col :span="6">
            <div class="icon-wrapper">
              <span class="lable-span">货品列表图标</span>
              <div class="product_img">
                <el-upload :show-file-list="false" class="avatar-uploader" :action="uploadUrl" :on-success="uploadIconSuccess" :before-upload="beforeUpload">
                  <img v-if="editingGood.gsicon!=''" :src="editingGood.gsicon" class="avatar"> </img>
                  <div v-else class="defaultproductimg"> </div>
                </el-upload>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="img-wrapper">
              <span class="lable-span">货品详情页图片</span>
              <div class="product_img">
                <el-upload :show-file-list="false" class="avatar-uploader" :action="uploadUrl" :on-success="uploadImageSuccess" :before-upload="beforeUpload">
                  <img v-if="editingGood.gsimage!=''" :src="editingGood.gsimage" class="avatar"> </img>
                  <div v-else class="defaultproductimg"> </div>
                </el-upload>
              </div>
            </div>
          </el-col>
        </el-row>
        <el-form-item label='介绍文案' prop='gsinfo'>
          <el-input v-model='editingGood.gsinfo' placeholder='请输入介绍文案'></el-input>
        </el-form-item>
        <el-form-item label='备注' prop='gsdescription'>
          <el-input v-model='editingGood.gsdescription' placeholder='请输入货品备注'></el-input>
        </el-form-item>
      </el-form>
      <div slot='footer' class='dialog-footer'>
        <el-button type='primary' @click='handleEditGoodSubmit'>确定</el-button>
        <el-button @click='editGoodDialogOpend = false'>取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
/* eslint-disable no-useless-escape */
import axios from 'axios';
import { Utils } from '@/utils/utils.js';
import NProgress from 'nprogress'; // Progress 进度条
export default {
  name: 'productset',
  data() {
    return {
      // 表格数据源
      gridDataSource: [],
      // 当前分页数据开始index
      startIndex: 0,
      // 当前分页数据结束index
      endIndex: 0,
      currentSelectedRow: null,
      gridDataIsLoading: false,
      // 分页配置
      paginationConfig: { selectedPageSize: 10, currentQueryPage: 0 },
      // 左树当前选中的product
      selectedGroup: 0,
      // 左樹的數據
      productgroups: [],
      // 左树的属性
      defaultProps: {
        children: 'children',
        label: 'groupname'
      },
      // 分组编辑窗体打开
      editGroupDialogOpend: false,
      // 是否开启验证
      groupValidateable: false,
      // group验证规则
      grouprules: {
        groupname: [
          { required: true, message: '店铺名称必填' },
          { type: 'string', max: 50, message: '微信productID必须小于50个字' }
        ]
      },
      // 当前编辑的group
      editingGroup: {
        groupname: '',
        grouptype: ''
      },
      // 当前正在编辑的货品信息
      editingGood: {
        gsid: 0,
        gsname: '',
        gsprice: 0,
        gsdescription: '',
        gsinfo: '',
        gsicon: '',
        gsimage: '',
        groupid: 0
      },
      // 货品编辑窗体打开
      editGoodDialogOpend: false,
      // 货品验证规则
      goodrules: {
        gsname: [
          { required: true, message: '店铺名称必填' },
          { type: 'string', max: 50, message: '微信productID必须小于50个字' }
        ]
      },
      goodValidateable: false
    };
  },
  methods: {
    onTreeSelected(selecteddata, selectednode) {
      this.selectedGroup = selecteddata.groupid;
    },
    RefreshTable() {
      NProgress.start();
      this.$http.get('/WechatMallOss/good/GetGoodsByGroup', {
        params: {
          groupid: this.selectedGroup
        }
      }).then((response) => {
        if (response.data.isSuccess) {
          this.gridDataSource = response.data.goods;
          NProgress.done();
        }
      }).catch(() => {
        NProgress.done();
      });
    },
    /**
     * 刷新树
     */
    InitTree() {
      this.$http.get('/WechatMallOss/Good/GetGroups').then((response) => {
        let children = [];
        if (response.data.isSuccess) {
          this.productgroups.splice(0, this.productgroups.length);
          response.data.groups.forEach((item) => {
            children.push(item);
          });
          this.productgroups.push({ groupid: 0, groupname: '全部分组', children: children });
        }
      });
    },
    computeDataIndex(pageNo, pageSize) {
      this.startIndex = pageSize * (pageNo - 1) + 1;
      this.endIndex = this.startIndex + pageSize;
    },
    /**
     * 分页变化
     */
    onPageSizeChanged(size) {
      this.paginationConfig.selectedPageSize = size;
      this.computeDataIndex(this.paginationConfig.currentQueryPage, size);
    },
    onPageNoChanged(page) {
      this.paginationConfig.currentQueryPage = page;
      this.computeDataIndex(page, this.paginationConfig.selectedPageSize);
    },
    /**
     * 表格selectchanged
     */
    onSelectionChanged(select) {
      this.currentSelectedRow = select;
    },
    renderContent(h, { node, data, store }) {
      if (data.groupid === 0) {
        return (
          <span>
            <span>
              <span>{node.label}</span>
            </span>
            <span style='float: right; margin-right: 20px'>
              <el-button type='success' size='mini' on-click={() => this.editgroup(store, data)}>添加</el-button>
            </span>
          </span>);
      } else {
        return (
          <span>
            <span>
              <span>{node.label}</span>
            </span>
            <span style='float: right; margin-right: 20px'>
              <el-button size='mini' type='info' on-click={() => this.editgroup(store, data)}>编辑</el-button>
              <el-button size='mini' type='danger' on-click={() => this.removegroup(store, data)}>删除</el-button>
            </span>
          </span>);
      }
    },
    closeGroupForm() {
      this.groupValidateable = false;
      this.$refs['groupForm'].resetFields();
    },
    editgroup(store, data) {
      this.$http.get('/WechatMallOss/Good/GetGroup', {
        params: {
          groupid: data.groupid
        }
      }).then((response) => {
        if (response.data.isSuccess) {
          this.editingGroup = response.data.group;
          this.editGroupDialogOpend = true;
        }
      });
    },
    removegroup(store, data) {
      let groupid = data.groupid;
      this.$confirm('删除该输入分组信息后,与此分组对应的货品关系将全部失效, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.delete('/WechatMallOss/Good/RemoveGroup', {
          params: {
            groupid: groupid
          }
        }).then(() => {
          this.$message({
            message: '移除成功!',
            type: 'success'
          });
          this.InitTree();
        });
      });
    },
    handleEditGroupSubmit() {
      this.groupValidateable = true;
      this.$refs.groupForm.validate((valid) => {
        if (valid) {
          this.$http.post('/WechatMallOss/good/SaveGroup', this.editingGroup).then((response) => {
            if (response.data.isSuccess) {
              this.$message({
                message: '保存成功!',
                type: 'success'
              });
              this.InitTree();
              this.editGroupDialogOpend = false;
            } else {
              this.$message({
                message: '数据提交出现错误,请稍后重试!',
                type: 'error'
              });
            }
          }).catch(() => {
            this.$message({
              message: '数据提交出现错误,请稍后重试!',
              type: 'error'
            });
          });
        } else {
          return false;
        }
      });
    },
    /**
     * 删除product
     */
    deletegood(index, row) {
      console.log(row);
      let gsid = row.basic.gsid;
      if (gsid) {
        this.$confirm('删除货品信息后,此货品将不能恢复, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http.delete('/WechatMallOss/good/deletegood', {
            params: {
              gsid: gsid
            }
          }).then((response) => {
            if (response.data.isSuccess) {
              this.gridDataSource.splice(index, 1);
              this.$message({
                message: '删除成功!',
                type: 'success'
              });
            }
          });
        }
          );
      }
    },
    // 关闭货品Form
    closeGoodForm() {
      this.goodValidateable = false;
      this.$refs['goodForm'].resetFields();
    },
    handleEditGoodSubmit() {
      this.goodValidateable = true;
      this.$refs.goodForm.validate((valid) => {
        if (valid) {
          this.$http.post('/WechatMallOss/good/SaveGood', this.editingGood).then((response) => {
            if (response.data.isSuccess) {
              this.$message({
                message: '保存成功!',
                type: 'success'
              });
              if (response.data.info) {
                let updateIndex = this.gridDataSource.findIndex((good) => {
                  return good.basic.gsid === response.data.info.basic.gsid;
                });
                if (updateIndex > -1) {
                  this.gridDataSource.splice(updateIndex, 1, response.data.info);
                } else {
                  this.gridDataSource.push(response.data.info);
                }
              }
              this.editGoodDialogOpend = false;
            } else {
              this.$message({
                message: '数据提交出现错误,请稍后重试!',
                type: 'error'
              });
            }
          }).catch(() => {
            this.$message({
              message: '数据提交出现错误,请稍后重试!',
              type: 'error'
            });
          });
        } else {
          return false;
        }
      });
    },
    editGood(row, isnew) {
      let gsid = 0;
      if (!isnew) {
        gsid = row.basic.gsid;
      }
      this.$http.get('/WechatMallOss/Good/GetGood', {
        params: {
          gsid: gsid
        }
      }).then((response) => {
        if (response.data.isSuccess) {
          this.editingGood = response.data.info.basic;
          this.editingGood.groupid = this.selectedGroup;
          this.editGoodDialogOpend = true;
        }
      });
    },
    uploadIconSuccess(res, file) {
      if (res.isSuccess && res.savedObjects) {
        this.editingGood.gsicon = axios.defaults.baseURL + '/img/get?img=' + res.savedObjects[0].fileName;
      }
    },
    uploadImageSuccess(res, file) {
      if (res.isSuccess && res.savedObjects) {
        this.editingGood.gsimage = axios.defaults.baseURL + '/img/get?img=' + res.savedObjects[0].fileName;
      }
    },
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    }
  },
  created() {
    this.InitTree();
  },
  watch: {
    selectedGroup(value) {
      this.RefreshTable(value);
    }
  },
  computed: {
    uploadUrl() {
      let jwt = Utils.GetLocalData('zillionossjwt');
      return axios.defaults.baseURL + '/img/upload?token=' + jwt;
    },
    gridPageList() {
      if (this.gridDataSource && this.gridDataSource.length > 0) {
        if (this.startIndex > 0 && this.endIndex > 0) {
          return this.gridDataSource.slice(this.startIndex - 1, this.endIndex - 1);
        } else {
          return [];
        }
      } else {
        return [];
      }
    },
    dataCount() {
      if (this.gridDataSource) {
        return this.gridDataSource.length;
      } else {
        return 0;
      }
    }
  }
};
</script>
<style rel='stylesheet/scss' lang='scss' scoped>
.app-container {
  height: 100%;
  .el-row {
    height: 100%;
    .el-col {
      height: 100%;
      .left-tree {
        height: 100%;
        .el-tree {
          height: 100%;
        }
      }
    }
  }
  .good-dialog {
    .lable-span {
      font-size: 14px;
      color: #48576a;
      font-weight: 700;
      margin-bottom: 12px;
    }
    .numinput {
      appearance: none;
    }
    .product_img {
      margin-top: 12px;
      width: 178px;
      height: 178px;
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      display: flex;
      align-items: center;
      justify-content: center;
      .avatar-uploader .el-upload:hover {
        border-color: #20a0ff;
      }
      .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
      }
      .avatar {
        width: 178px;
        height: 178px;
      }
      .defaultproductimg {
        width: 130px;
        height: 130px;
        background-repeat: no-repeat;
        border: none;
        background-image: url('./defaultproduct.png');
      }
    }
  }
}
</style>
